// pages/trend/trend.js
import * as echarts from '../../ec-canvas/echarts';
import {GetFatDetailList} from "../../api/api";
import getNextDate from "../../utils/getNextDate";
import {getCurrentDate} from "../../utils/timeTool";
import countDay from "../../utils/countDay";

function setOption(chart,currentTypeDate,currentDateData){
  var option = {
    color: ["#fff"],
    // legend: {
    //   data: ['体重(KG)', '脂肪比(%)'],
    //   orient: 'horizontal',  
    //   top: 10,
    //   left: 'center',
    //   z: 100
    // },
    grid: {
      containLabel: true,
      top: '18%',   // 等价于 y: '16%'
      left: '3%', 
      right: '5%',
      bottom: '3%',
    },
    tooltip: {
      show: true,
      trigger: 'axis',
    },
    xAxis: {//轴名标注
      type: 'category',
      boundaryGap: false,
      data: currentDateData,
      // show: false
      axisLine: { //x轴的设置
        lineStyle: {
            color: "#fff" //x轴的颜色。
        }
      },
      axisLabel: {//x轴文字设置
        textStyle: {
            fontSize: 10, //文字的字体大小
            color: "#fff"
        },
      },

    },
    yAxis: {//直角坐标系中的纵轴
      x: 'center',
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color:"#dcd9fa"
        }
      },
      axisLine: {
        lineStyle: {
            color: "#8279ea" //y轴的颜色。
        }
      },
      axisLabel: {//x轴文字设置
        textStyle: {
            fontSize: 10, //文字的字体大小
            color: "#fff"
        },
      },
  
    },
    
    series: [{
      name: currentTypeDate.name,
      type: 'line',
      smooth: true,
    //   areaStyle:{
    //     normal:{
    //       //颜色渐变函数 前四个参数分别表示四个位置依次为左、下、右、上
    //         color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ 

    //             offset: 0,
    //             color: 'rgba(80,141,255,0.39)'
    //         }, {
    //             offset: .34,
    //             color: 'rgba(56,155,255,0.25)'
    //         },{
    //             offset: 1,
    //             color: 'rgba(38,197,254,0.00)'
    //         }])

    //     }
    // },//区域颜色渐变
      data: currentTypeDate.data
    }
  ]
  };
  chart.setOption(option);
}


Page({

  /**
   * 页面的初始数据
   */
  data: {
    ec: {
      // onInit: initChart
      lazyLoad: true
    },
    // typeData:[
    //   {
    //     name:"体重(kg)",
    //     data:[60, 50, 45, 62, 78, 80, 103]
    //   },
    //   {
    //     name:"脂肪%",
    //     data:[10,30, 15, 22, 18, 23, 8]
    //   },
    //   {
    //     name:"肌肉%",
    //     data:[70,80, 85, 29, 48, 53, 80]
    //   },
    // ],
    // dateData:[
    //   ['04/14', '04/15'],
    //   ['04/14', '04/15', '04/16'],
    //   ['04/14', '04/15', '04/16', '04/17', '04/18', '04/19', '04/20']
    // ],
    dateDatas:[],
    typeDatas:[],

    typeActiveIndex:0,
    dateActiveIndex:0,
    dayNum:0,
    weightChange:0,
    pbfChange:0,
    muscleChenge:0,
    typeFlag:true,
    dateFlag:true,
  },


  toggleTypeActive(e){
    let index=e.target.dataset.index;
      // 判断是否按的是同一个按钮 是就不重复生成图表
      if(index==this.data.typeActiveIndex){
        return;
      }
      if (this.data.typeFlag) {
        this.setData({
          typeActiveIndex:index,
          typeFlag:false
        })
        setTimeout(()=>{
          this.setData({
            typeFlag:true
          })
        },800)
        if (this.data.typeDatas.length>0) {
          this.ecComponent = this.selectComponent('#mychart-dom-line');
          this.init();
        }

      }

  },
  toggleDateActive(e){
    let index=e.target.dataset.index;
    if(index==this.data.dateActiveIndex){
      return;
    }
    if (this.data.dateFlag) {
      this.setData({
        dateActiveIndex:index,
        dateFlag:false
      })
      setTimeout(()=>{
        this.setData({
          dateFlag:true
        })
      },800)
      switch (index) {
        case "0":
          this.getData(-7);
          break;
        case "1":
          this.getData(-30);
          break;
        case "2":
          this.getData(-90);
          break;
      }
    }
     
  },

  // function initChart(canvas, width, height, dpr) {
//   // const chart = echarts.init(canvas, null, {
//   //   width: width,
//   //   height: height,
//   //   devicePixelRatio: dpr // new
//   // });
//   // canvas.setChart(chart);

  // 初始化可视化图标
  init(){

    let {typeDatas,dateDatas,typeActiveIndex,dateActiveIndex}=this.data;
    let currentTypeData=typeDatas[typeActiveIndex];
    let currentDateData=dateDatas;
    this.ecComponent.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      setOption(chart,currentTypeData,currentDateData);
     

      return chart;
    });
  },
  getData(agodata){
    let TZCuserInfo=wx.getStorageSync('TZCuserInfo');
    if(TZCuserInfo){
      let startDate=getNextDate(getCurrentDate().date,agodata);
      let endDate=getNextDate(getCurrentDate().date,1);
      let data={
        fatid: TZCuserInfo.id,
        startdate: startDate,
        enddate: endDate,
      };
      wx.showLoading({
        title: '加载中',
        mask:true
      })
      GetFatDetailList(data,(e)=>{
        wx.hideLoading();
        let dateDatas=[];
        let day_num=[];
        let typeDatas=[
          {
            name:"体重(kg)",
            data:[]
          },
          {
            name:"脂肪%",
            data:[]
          },
          {
            name:"肌肉%",
            data:[]
          },
        ];
        if (e.data) {
          e.data.forEach((val,index)=>{
            //过滤 日期  把日期去重
            if(day_num.indexOf(val.createdate.substring(5,10))==-1){
              day_num.push(val.createdate.substring(5,10));
             }
              dateDatas.push(val.createdate.substring(5,10));
              typeDatas[0].data.push(val.weight);
              typeDatas[1].data.push(val.pbf);
              typeDatas[2].data.push(val.rateOfMuscle);
          })
          
          let startDayData= e.data[0];
          let endDayData= e.data[e.data.length-1];
          // let dayNum=countDay(startDayData.createdate.substring(0,10),endDayData.createdate.substring(0,10));
          let dayNum=day_num.length;
          let weightChange=(endDayData.weight - startDayData.weight).toFixed(1);
          let pbfChange=(endDayData.pbf - startDayData.pbf).toFixed(1);
          let muscleChenge=(endDayData.rateOfMuscle - startDayData.rateOfMuscle).toFixed(1);
          this.setData({
            dateDatas,
            typeDatas,
            dayNum,
            weightChange,
            pbfChange,
            muscleChenge,
          })
          this.ecComponent = this.selectComponent('#mychart-dom-line');
          this.init();
        }
       
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getData(-7);


      
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})